import { useEffect, useRef, useState } from "react"
import SickbedTab from "../../components/SickbedTab"
import { DeleteOutlined, FormOutlined, SearchOutlined } from "@ant-design/icons";
import { Select, Space, TableColumnsType, DatePicker } from "antd";
import { Input, Button, Modal, message } from 'antd';
import { handleDrugsList, handleDrugsDel, handleEditDrugs,handleSearchDrugs } from '../../api/Drugs/DrugsApi'
import { useDispatch, useSelector } from "react-redux";
import '../../assets/css/Drugs/drugsManage.css'
import BatchDel from "../../components/BatchDel";
import { getDrugsListDel, getEditDrugsList, getSearchDrugs, getcountSub, getcountAdd, getpriceSub, getpriceAdd, getDrugsData } from '../../stores/drugsManage'
import moment from "moment";
import Pagination from "../../components/Pagination";
import customParseFormat from 'dayjs/plugin/customParseFormat';
import dayjs from 'dayjs';

interface DataType {
    id: React.Key;
    drugsname?: string;
    sort: string;
    img?: string;
    type?: string;
    count?: number;
    price?: number;
    starttime?: string;
    endtime?: string;
}
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY/MM/DD';
export default function DrugManage() {


    const drugsData = useSelector(state => state.drugsManage.drugsList)
    const dispatch = useDispatch()

    // const [formattedData, setFormattedData] = useState<DataType[]>([]);
    const [drugsId, setDrugsId] = useState()
    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('你正在删除药品，此操作不可逆，确定删除吗？');
    const [drugsEdit, setDrigsEdit] = useState(false)
    const [searchDrugsname, setSearchDrugsname] = useState('')
    const [searchSort, setSearchSort] = useState('')
    const [editingItem, setEditingItem] = useState<DataType | null>(null);
    const [paginationInfo, setPaginationInfo] = useState({ current: 1, pageSize: 5 });
    const [messageApi, contextHolder] = message.useMessage();
    const drugsRef = useRef(null)
    drugsRef.current = drugsId

    useEffect(() => {
        const DrugsList = async () => {
            const drugsList = await handleDrugsList({ page: 1, size: 100 })
            if (drugsList) {
                dispatch(getDrugsData(drugsList.data))
                // localStorage.setItem('drugsList', JSON.stringify(drugsList.data))
            }
        }
        DrugsList()
    }, [])

    const columns: TableColumnsType<DataType> = [
        { title: '医品名称', dataIndex: 'drugsname' },
        { title: '医品分类', dataIndex: 'sort' },
        { title: '医品图片', dataIndex: 'img' },
        { title: '医品规格', dataIndex: 'type' },
        { title: '库存数量', dataIndex: 'count' },
        { title: '医品价格', dataIndex: 'price' },
        { title: '生产日期', dataIndex: 'starttime' },
        { title: '有效日期', dataIndex: 'endtime' },
        { title: '操作', dataIndex: 'btn' },
    ];

    const dataSource = drugsData.map<DataType>((item: DataType) => ({
        key: item.id,
        drugsname: <>{drugsEdit && item.id === drugsId ? <Input style={{ width: '7.5vw' }} value={editingItem?.drugsname || item.drugsname} onChange={(e) => setEditingItem((prev) => ({ ...prev, drugsname: e.target.value }))} /> : item.drugsname}</>,
        sort: <>{drugsEdit && item.id === drugsId ?
            <Space wrap>
                <Select
                    defaultValue={item.sort}
                    style={{ width: 100 }}
                    onChange={(value) => {
                        setEditingItem((prev): DataType => ({ ...prev, sort: value }));
                    }}
                    options={[
                        { value: '疫苗类', label: '疫苗类' },
                        { value: '耗材', label: '耗材' },
                        { value: '药品', label: '药品' },
                        { value: '中药', label: '中药' },
                        { value: '西药', label: '西药' },
                    ]}
                />
            </Space> : item.sort}</>,
        img: <img className="drugimg" src={item.img}></img>,
        type: <>{drugsEdit && item.id === drugsId ? <Input style={{ width: '7vw', height: '4vw' }} value={editingItem?.type || item.type} onChange={(e) => setEditingItem((prev) => ({ ...prev, type: e.target.value }))} /> : item.type}</>,
        count: <>{drugsEdit && item.id === drugsId ?
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ fontSize: '1.5vw' }} onClick={() => handleCountSub(item.id)}>-</div>
                <input type="number" style={{ width: '2.5vw', margin: "0 2px", height: '1vw' }} value={editingItem?.count || item.count} onChange={(e) => setEditingItem((prev) => ({ ...prev, count: e.target.value }))}></input>
                <div style={{ fontSize: '1.5vw' }} onClick={() => handleCountAdd(item.id)}>+</div>
            </div>
            : item.count}</>,
        price: <>{drugsEdit && item.id === drugsId ?
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ fontSize: '1.5vw' }} onClick={() => handlePriceSub(item.id)}>-</div>
                <input type="number" style={{ width: '2.5vw', margin: "0 2px", height: '1vw' }} value={editingItem?.price || item.price} onChange={(e) => setEditingItem((prev) => ({ ...prev, price: e.target.value }))}></input>
                <div style={{ fontSize: '1.5vw' }} onClick={() => handlePriceAdd(item.id)}>+</div>
            </div>
            : item.price}</>,
        starttime: <>{drugsEdit && item.id === drugsId ?
            <Space direction="vertical" size={5}>
                <DatePicker defaultValue={dayjs(item.starttime, dateFormat)} format={dateFormat} onChange={(date, dateString) => setEditingItem((prev) => ({ ...prev, starttime: dateString }))} />
            </Space>
            : moment(item.starttime).format('YYYY-M-D')}</>,
        endtime: <>{drugsEdit && item.id === drugsId ?
            <Space direction="vertical" size={5}>
                <DatePicker defaultValue={dayjs(item.endtime, dateFormat)} format={dateFormat} onChange={(date, dateString) => setEditingItem((prev) => ({ ...prev, endtime: dateString }))} />
            </Space>
            : moment(item.endtime).format('YYYY-M-D')}</>,
        btn: <>
            {drugsEdit && item.id === drugsId ?
                <div>
                    <DeleteOutlined style={{ color: '#409EFF', paddingRight: '8px' }} onClick={() => handleDel(item.id)} />
                    <FormOutlined style={{ color: '#409EFF' }} onClick={() => hideModalEdit(item.id)} />
                </div>
                : <div>
                    <DeleteOutlined style={{ color: '#409EFF', paddingRight: '8px' }} onClick={() => handleDel(item.id)} />
                    <FormOutlined style={{ color: '#409EFF' }} onClick={() => showModalEdit(item)} />
                </div>
            }
        </>,
    }))

    const showModalEdit = (item: any): void => {
        setDrugsId(item.id)
        setDrigsEdit(!drugsEdit)
        setEditingItem(item)
    }

    const hideModalEdit = async (id: any): Promise<void> => {
        const editItem = { ...editingItem, id }

        setDrugsId(id)
        dispatch(getEditDrugsList(editItem))

        const editDrugs = await handleEditDrugs({
            id: id,
            name: editItem.drugsname,
            sort: editItem.sort,
            type: editItem.type,
            starttime: moment(editItem.starttime).format('YYYY-M-D'),
            endtime: moment(editItem.endtime).format('YYYY-M-D'),
            count: editItem.count,
            price: editItem.price,
            img: editItem.img
        })
        console.log(editDrugs);
        if (editDrugs.code === 1) {
            messageApi.open({
                type: 'success',
                content: editDrugs.msg,
            });
        } else {
            messageApi.open({
                type: 'warning',
                content: editDrugs.msg,
            });
        }

        setDrigsEdit(!drugsEdit)
    }

    const handleCountSub = (id: any) => {
        console.log(id);
        dispatch(getcountSub(id))
    }

    const handleCountAdd = (id: any) => {
        console.log(id);
        dispatch(getcountAdd(id))
    }

    const handlePriceSub = (id: any) => {
        console.log(id);
        dispatch(getpriceSub(id))
    }

    const handlePriceAdd = (id: any) => {
        console.log(id);
        dispatch(getpriceAdd(id))
    }

    const handleDel = (id: any): void => {
        setDrugsId(id)
        setTimeout(() => {
            console.log(drugsRef.current);
        }, 0);
        setOpen(true);
    }

    const handleDelOk = () => {
        setConfirmLoading(true);
        setTimeout(async () => {
            dispatch(getDrugsListDel(drugsRef.current))
            setOpen(false);
            setConfirmLoading(false);
            const drugsDel = await handleDrugsDel({ id: drugsRef.current })
            console.log(drugsDel);
            if(drugsDel.code===1){
                messageApi.open({
                    type: 'success',
                    content: drugsDel.msg,
                  });
            }else{
                messageApi.open({
                    type: 'warning',
                    content: drugsDel.msg,
                  });
            }
        }, 1000);
    };

    const handleDelCancel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };

    const handleSearch = async () => {
        dispatch(getSearchDrugs({
            drugsname: searchDrugsname,
            sort: searchSort
        }))
        const searchDrugs= await handleSearchDrugs({page:1,size:100,name:searchDrugsname,sort:searchSort})
        console.log(searchDrugs);
        if(searchDrugs.code===1){
            messageApi.open({
                type: 'success',
                content: searchDrugs.msg,
              });
        }else{
            messageApi.open({
                type: 'warning',
                content: searchDrugs.msg,
              });
        }
        
    }

    const handleTableChange = (page: number, pageSize: number) => {
        setPaginationInfo({ ...paginationInfo, current: page, pageSize: pageSize });
    };



    return (
        <>
            {contextHolder}
            <div className="drugs">
                <div className="drugs-header">
                    <div className="drugs-header-search">
                        <span className="drugs-header-search-name">医品名称</span>
                        <Input value={searchDrugsname} onChange={(e) => setSearchDrugsname(e.target.value)} placeholder="请输入医疗品/耗材/药品名称" />
                        <span className="drugs-header-search-name">医品分类</span>
                        <Input value={searchSort} onChange={(e => setSearchSort(e.target.value))} placeholder="请输入医疗品/耗材/药品分类" />
                        <Button type="primary" onClick={handleSearch} icon={<SearchOutlined />}>
                            查询
                        </Button>
                    </div>
                    <div>
                        <BatchDel selectedRowKeys={JSON.parse((localStorage as any).getItem('newSelectedRowKeys'))}></BatchDel>
                    </div>
                </div>
                <div className="drugs-table">
                    <SickbedTab columns={columns} dataSource={dataSource} onFetchData={drugsData} pagination={paginationInfo}></SickbedTab>
                    <Pagination listData={drugsData} onChange={handleTableChange}></Pagination>
                </div>
                <Modal
                    title="系统提示"
                    open={open}
                    onOk={handleDelOk}
                    confirmLoading={confirmLoading}
                    onCancel={handleDelCancel}
                >
                    <p>{modalText}</p>
                </Modal>
            </div>
        </>
    )
}

